package cn.com.majiang.interceptor;


import cn.com.majiang.domain.Manager;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by jiangyanxin on 2017/3/20.
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    public static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    private String loginUrl;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("登陆拦截器,请求url为"+request.getServletPath());
        HttpSession session = request.getSession();
        Manager manager = (Manager)session.getAttribute("manager");
        Integer id = (Integer)session.getAttribute("id");
        if(manager == null || id == null){
            logger.info("没有登录需要重新登录"+loginUrl);
            response.sendRedirect(loginUrl);
            return false;
        }else{
            logger.info("登录人为"+id+"信息："+ JSON.toJSONString(manager));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {

        this.loginUrl = loginUrl;
        logger.info("setloginUrl"+loginUrl);
    }

}
